package com.wl156.activities.find;

import java.io.IOException;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.xmlpull.v1.XmlPullParserException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.wl156.BaseActivity;
import com.wl156.MyApp;
import com.wl156.R;
import com.wl156.activities.order.NewOrder;
import com.wl156.model.Certificate;
import com.wl156.model.WebServiceClient;
import com.wl156.utils.Utils;

public class CarInfo extends BaseActivity implements OnClickListener {

	private Button mCollect;

	private TextView mCurrentPlace;
	private TextView mDriverName;
	private ImageButton mDriverDial;
	private TextView mOwnerName;
	private ImageButton mOwnerDial;
	private TextView mCarCode;
	private TextView mCarType;
	private TextView mCarLength;
	private TextView mCarWeight;
	private TextView mNeed;
	private TextView mOftenRun;
	private TextView mCreditScore;
	private TextView mFinishOrderCount;

	private long mCarId;

	private WebServiceClient mWebServiceClient;
	private Certificate mCertificate;

	boolean mIsOrderSelect;
	Button mOrderSelect;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_car_info);

		mWebServiceClient = new WebServiceClient(this);
		mCertificate = ((MyApp) getApplication()).getCertificateFromXml();

		mCarId = getIntent().getLongExtra("id", 0);

		mCollect = (Button) findViewById(R.id.collect);
		mCollect.setOnClickListener(this);

		mCurrentPlace = (TextView) findViewById(R.id.current_place);
		mDriverName = (TextView) findViewById(R.id.driver_name);
		mDriverDial = (ImageButton) findViewById(R.id.driver_dial);
		mDriverDial.setOnClickListener(this);
		mOwnerName = (TextView) findViewById(R.id.owner_name);
		mOwnerDial = (ImageButton) findViewById(R.id.owner_dial);
		mOwnerDial.setOnClickListener(this);
		mCarCode = (TextView) findViewById(R.id.car_code);
		mCarType = (TextView) findViewById(R.id.car_type);
		mCarLength = (TextView) findViewById(R.id.car_length);
		mCarWeight = (TextView) findViewById(R.id.car_weight);
		mNeed = (TextView) findViewById(R.id.need);
		mOftenRun = (TextView) findViewById(R.id.often_run);
		mCreditScore = (TextView) findViewById(R.id.credit_score);
		mFinishOrderCount = (TextView) findViewById(R.id.finish_order_count);

		mOrderSelect = (Button) findViewById(R.id.order_select);
		mOrderSelect.setOnClickListener(this);

		mIsOrderSelect = getIntent().getBooleanExtra("order_select", false);
		if (mIsOrderSelect) {
			mOrderSelect.setVisibility(View.VISIBLE);
		} else {
			mOrderSelect.setVisibility(View.GONE);
		}

		new AsyncTask<Void, Void, Object>() {
			ProgressDialog mDialog;

			@Override
			protected void onPostExecute(Object result) {
				// 03-04 09:17:40.996: D/(10259): result: anyType{string=1;
				// string=张三; string=15644889967; string=anyType{}; string=张大宝;
				// string=13977441122; string=粤C88888; string=前四后四; string=15;
				// string=12; string=可以运输易碎品; string=广东省广州市白云区;
				// string=广东广州|云南昆明;广东广州|河南;; string=5; string=1; }, type:
				// SoapObject

				try {
					if (result instanceof SoapObject) {
						SoapObject so = (SoapObject) result;
						String id = Utils.propertyToShow(so.getProperty(0));
						String driverName = Utils.propertyToShow(so
								.getProperty(1));
						String driverPhone = Utils.propertyToShow(so
								.getProperty(2));
						String driverPhoneShort = Utils.propertyToShow(so
								.getProperty(3));
						String ownerName = Utils.propertyToShow(so
								.getProperty(4));
						String ownerPhone = Utils.propertyToShow(so
								.getProperty(5));
						String carCode = Utils
								.propertyToShow(so.getProperty(6));
						String carType = Utils
								.propertyToShow(so.getProperty(7));
						String carWeigth = Utils.propertyToShow(so
								.getProperty(8));
						String carLength = Utils.propertyToShow(so
								.getProperty(9));
						String need = Utils.propertyToShow(so.getProperty(10));
						String currentPlace = Utils.propertyToShow(so
								.getProperty(11));
						String oftenLine = Utils.propertyToShow(so
								.getProperty(12));
						String creditScore = Utils.propertyToShow(so
								.getProperty(13));
						String finishOrderCount = Utils.propertyToShow(so
								.getProperty(14));

						MyApp.sCarInfo.id = id;
						MyApp.sCarInfo.driverName = driverName;
						MyApp.sCarInfo.driverPhone = driverPhone;
						MyApp.sCarInfo.driverPhoneShort = driverPhoneShort;
						MyApp.sCarInfo.ownerName = ownerName;
						MyApp.sCarInfo.ownerPhone = ownerPhone;
						MyApp.sCarInfo.carCode = carCode;
						MyApp.sCarInfo.carType = carType;
						MyApp.sCarInfo.carWeigth = carWeigth;
						MyApp.sCarInfo.carLength = carLength;
						MyApp.sCarInfo.need = need;
						MyApp.sCarInfo.currentPlace = currentPlace;
						MyApp.sCarInfo.oftenLine = oftenLine;
						MyApp.sCarInfo.creditScore = creditScore;
						MyApp.sCarInfo.finishOrderCount = finishOrderCount;

						mDriverName.setText(driverName);
						mDriverDial.setTag(driverPhone);
						mOwnerName.setText(ownerName);
						mOwnerDial.setTag(ownerPhone);
						mCarCode.setText(carCode);
						mCarType.setText(carType);
						mCarWeight.setText(carWeigth);
						mCarLength.setText(carLength);
						mNeed.setText(need);
						mCurrentPlace.setText(currentPlace);
						String[] lines = oftenLine.split(";");
						StringBuilder sb = new StringBuilder();
						try {
							for (String line : lines) {
								int index = line.indexOf("|");
								// String[] places = line.split("|");
								sb.append(line.subSequence(0, index));
								sb.append("——");
								sb.append(line.subSequence(index + 1,
										line.length()));
								sb.append("\n");
							}
						} catch (Exception e) {
						}
						mOftenRun.setText(sb.toString());
						mCreditScore.setText(creditScore);
						mFinishOrderCount.setText(finishOrderCount);
					} else {
						Toast.makeText(CarInfo.this, "获取信息失败，请稍候再试",
								Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) {
					Toast.makeText(CarInfo.this, "获取信息失败，请稍候再试",
							Toast.LENGTH_LONG).show();
				}
				mDialog.dismiss();
			};

			@Override
			protected void onPreExecute() {
				mDialog = ProgressDialog.show(CarInfo.this, "", "加载中");
			};

			@Override
			protected Object doInBackground(Void... params) {
				try {
					return mWebServiceClient.commonFindTrunkDetail(
							mCertificate, mCarId);
				} catch (IOException e) {
					return e;
				} catch (XmlPullParserException e) {
					return e;
				}
			}
		}.execute();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.order_select: {
			Intent i = new Intent(this, NewOrder.class);
			i.putExtra("carId", mCarId);
			startActivity(i);
		}
			break;
		case R.id.owner_dial:
		case R.id.driver_dial:
			Intent i = new Intent(Intent.ACTION_DIAL);
			i.setData(Uri.parse("tel:" + v.getTag().toString()));
			startActivity(i);
			break;
		case R.id.collect:
			new AsyncTask<Void, Void, Object>() {
				ProgressDialog mDialog;

				@Override
				protected void onPreExecute() {
					mDialog = ProgressDialog.show(CarInfo.this, "", "加载中");
				};

				@Override
				protected void onPostExecute(Object result) {
					if (result instanceof SoapObject) {
						SoapObject so = (SoapObject) result;
						final String[] ids = new String[so.getPropertyCount()];
						String[] names = new String[so.getPropertyCount()];
						String[] counts = new String[so.getPropertyCount()];
						for (int i = 0; i < so.getPropertyCount(); i++) {
							SoapObject line = (SoapObject) so.getProperty(i);
							String id = line.getPropertyAsString(0);
							ids[i] = id;
							String name = line.getPropertyAsString(1);
							names[i] = name;
							String count = line.getPropertyAsString(2);
							counts[i] = count;
						}

						AlertDialog.Builder builer = new Builder(CarInfo.this);
						builer.setItems(names,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											final int which) {
										new AsyncTask<Void, Void, Object>() {
											ProgressDialog mDialog;

											@Override
											protected void onPreExecute() {
												mDialog = ProgressDialog
														.show(CarInfo.this, "",
																"添加中");
											};

											@Override
											protected void onPostExecute(
													Object result) {
												if (result instanceof SoapObject) {
													SoapObject so = (SoapObject) result;
													Toast.makeText(
															CarInfo.this,
															"收藏成功",
															Toast.LENGTH_LONG)
															.show();
												} else if (result instanceof SoapPrimitive) {
													Toast.makeText(
															CarInfo.this,
															result.toString(),
															Toast.LENGTH_LONG)
															.show();
												} else {
													Toast.makeText(
															CarInfo.this,
															"网络异常，添加失败，请稍候再试",
															Toast.LENGTH_LONG)
															.show();
												}
												mDialog.dismiss();
											};

											@Override
											protected Object doInBackground(
													Void... params) {
												try {
													return mWebServiceClient
															.companyModifyStoreGroupAddTruckToGroup(
																	mCertificate,
																	String.valueOf(mCarId),
																	ids[which]);
												} catch (IOException e) {
													return e;
												} catch (XmlPullParserException e) {
													return e;
												}
											}
										}.execute();
									}
								});
						builer.show();
					} else {
						Toast.makeText(CarInfo.this, "联网失败，请稍候再试",
								Toast.LENGTH_LONG).show();
					}
					mDialog.dismiss();
				};

				@Override
				protected Object doInBackground(Void... params) {
					try {
						return mWebServiceClient
								.commonGetMyStoreGroups(mCertificate);
					} catch (IOException e) {
						return e;
					} catch (XmlPullParserException e) {
						return e;
					}
				}
			}.execute();
			break;
		}
	}

	// class CategoryAdapter extends BaseAdapter {
	//
	// public CategoryAdapter() {
	// }
	//
	// @Override
	// public int getCount() {
	// return 0;
	// }
	//
	// @Override
	// public Object getItem(int position) {
	// return null;
	// }
	//
	// @Override
	// public long getItemId(int position) {
	// return 0;
	// }
	//
	// @Override
	// public View getView(int position, View convertView, ViewGroup parent) {
	// return null;
	//
	// }
	// }
}
